import com.example.demo1.reposity.ArticleListResponse
import com.example.demo1.reposity.ArticleReadList
import com.example.demo1.reposity.ArticleTypeListResponse
import com.example.demo1.reposity.SelectListResponse
import okhttp3.OkHttpClient
import okhttp3.Request
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import java.security.cert.X509Certificate
import javax.net.ssl.*
/**
 * 定义了多个网络请求方法，用于从服务器获取不同类型的数据。
 * 这些方法将使用 Retrofit 库将 HTTP 请求转换为相应的Kotlin 函数调用
 * **/
interface ApiService {
    @GET("englishgpt/library/articleTypeList")
    fun getArticleTypeList(): Call<ArticleTypeListResponse>

    @GET("englishgpt/appArticle/selectList")
    fun getSelectList(): Call<SelectListResponse>

    @GET("knowledge/article/getArticleDetail")
    fun getReadArticleList(
        @Query("aid") aid: Int?=6,
    ): Call<ArticleReadList>

    @GET("englishgpt/library/articleList")
    fun getArticleList(
        @Query("lexile") lexile: Int?,
        @Query("typeId") typeId: Int?,
        @Query("page") page: Int,
        @Query("size") size: Int
    ): Call<ArticleListResponse>

    companion object {
        private const val BASE_URL = "https://test.shiqu.zhilehuo.com/"

        fun create(cookie:String): ApiService {
            // 设置忽略 SSL 验证的 TrustManager
            val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
            })

            // 初始化 SSLContext 并设置为信任所有证书
            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, java.security.SecureRandom())

            // 创建一个不安全的 HostnameVerifier
            val hostnameVerifier = HostnameVerifier { _, _ -> true }

            // 配置 OkHttpClient
            val client = OkHttpClient.Builder()
                .sslSocketFactory(sslContext.socketFactory, trustAllCerts[0] as X509TrustManager)
                .hostnameVerifier(hostnameVerifier) // 忽略主机名校验
                .addInterceptor { chain ->
                    val original: Request = chain.request()
                    val request: Request = original.newBuilder()
                        .header("Cookie", cookie)
                        .build()
                    chain.proceed(request)
                }
                .build()

            val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

            return retrofit.create(ApiService::class.java)
        }
    }
}
